package cn.lili.modules.payment.serviceimpl;

import cn.lili.common.security.AuthUser;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.utils.StringUtils;
import cn.lili.common.vo.PageVO;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.payment.entity.RefundLog;
import cn.lili.modules.payment.entity.vo.RefundLogVO;
import cn.lili.modules.payment.mapper.RefundLogMapper;
import cn.lili.modules.payment.service.RefundLogService;
import cn.lili.modules.permission.entity.dos.AdminUser;
import cn.lili.modules.permission.service.AdminUserService;
import cn.lili.mybatis.util.PageUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 退款日志 业务实现
 *
 * @author Chopper
 * @since 2020-12-19 09:25
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RefundLogServiceImpl extends ServiceImpl<RefundLogMapper, RefundLog> implements RefundLogService {

	@Autowired
	private AdminUserService adminUserService;

	@Autowired
	private PartnerService partnerService;

	@Override
	public RefundLog queryByAfterSaleSn(String sn) {
		return this.getOne(new LambdaUpdateWrapper<RefundLog>().eq(RefundLog::getAfterSaleNo, sn));
	}

	@Override
	public IPage<RefundLogVO> getPage(PageVO pageVO, QueryWrapper<RefundLogVO> queryWrapper) {
		AuthUser currentUser = UserContext.getCurrentUser();
		// 如果当前会员不为空，且为代理商角色
		if (currentUser != null && (currentUser.getRole().equals(UserEnums.AGENT))) {
			// AdminUser adminUser = adminUserService.getById(currentUser.getId());
			// if (null != adminUser) {
			// queryWrapper.eq("e.extension", adminUser.getPromotionCode());
			// }
			// 查询合伙人区域
			LambdaQueryWrapper<Partner> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Partner::getMemberId, currentUser.getMemberId());
			lambdaQueryWrapper.eq(Partner::getDeleteFlag, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerState, 0);
			lambdaQueryWrapper.eq(Partner::getPartnerType, 4);
			Partner partner = partnerService.getOne(lambdaQueryWrapper);
			if (null != partner && StringUtils.isNotEmpty(partner.getRegionId())) {
				queryWrapper.eq("s.ad_code", partner.getRegionId());
			}
		}
		return this.baseMapper.getPageList12(PageUtil.initPage(pageVO), queryWrapper);
	}
}